package hotLeetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class H06Leetcode15 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        if (nums[0] > 0) {
            return result;
        }
        int len = nums.length;


        for (int i = 0; i < len; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int l = i + 1, r = len - 1;
            while (l < r) {

                int sum = nums[i] + nums[l] + nums[r];
                if (sum > 0) {
                    r--;
                } else if (sum < 0) {
                    l++;
                } else {
                    result.add(new ArrayList<>(Arrays.asList(nums[i], nums[l], nums[r])));
                    while (l < r && nums[l] == nums[l + 1]) {
                        l++;
                    }
                    while (l < r && nums[r -1] == nums[r]) {
                        r--;
                    }
                    l++;
                    r--;
                }
            }


        }

        return result;

    }


    public static void main(String[] args) {
        H06Leetcode15 h06Leetcode15 = new H06Leetcode15();
        int[] nums = {-1, 0, 1, 2, -1, -4};
        System.out.println(h06Leetcode15.threeSum(nums));

    }
}
